package com.itlong.cloud.controller.current;

import com.alibaba.fastjson.JSONArray;
import com.itlong.cloud.POJO.DTO.app.AppPadBotRobotDTO;
import com.itlong.cloud.POJO.DTO.property.PropertyPadBotDeliveryTaskDTO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.app.AppUserCacheVO;
import com.itlong.cloud.POJO.VO.property.PropertyDeliveryTaskGetPageVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.annotation.UnAuthAccessRequired;
import com.itlong.cloud.annotation.UnParamEncrypt;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.enumerate.ecode.AppErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.iottp.IPadBotRobotServiceClient;
import com.itlong.cloud.project.property.IPropertyDeliveryTaskServiceClient;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.user.app.IAppUserInfoCacheServiceClient;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.page.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * <desc>
 *      派宝机器人指令控制器
 * </desc>
 *
 * @createDate 2021/1/6
 **/
@RestController
@RequestMapping("/h5/padbot")
public class AppPadBotRobotController {


    @Value("${" + PlatformConstants.APP_REQUEST_PARAMS_ENCRYPT_KEY + "}")
    public String APP_REQUEST_PARAMS_ENCRYPT_KEY;

    @Autowired
    private IPadBotRobotServiceClient iPadBotRobotServiceClient;

    @Autowired
    private IPropertyDeliveryTaskServiceClient iPropertyDeliveryTaskServiceClient;

    @Autowired
    private IAppUserInfoCacheServiceClient userCache;

    @Autowired
    private RedisService redisService;

    //前台目标点地址
    public static final String RECEPTION = "2c928aa576f5b4cd0176f6729f621983";

    public static final String SOFTWARE_DEPARTMENT = "2c928aa576f5b4cd0176f67361a81997";
    /**
     * <desc>
     *      获取目标点列表
     * </desc>
     *
     * @param appPadBotRobotDTO 派宝机器人传参DTO
     * @return
     * @Author Zhu.yj
     * @createDate  2021/1/6
     */
    @UnAuthAccessRequired
    @PostMapping("getTargetPointList")
    public Object getTargetPointList(AppPadBotRobotDTO appPadBotRobotDTO, HttpServletRequest request){
        try {
            appPadBotRobotDTO = HttpProtocolUtil.parseRequestParamToDTO(AppPadBotRobotDTO.class, request);

            if (appPadBotRobotDTO == null){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            List<Map<String, Object>> targetPointList = iPropertyDeliveryTaskServiceClient.getTargetPointList(null);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),targetPointList);
        }catch (Exception e){
            throw new DataAccessException("【派宝机器人getTargetPointList】获取目标点列表失败", e);
        }
    }

    /**
     * <desc>
     *      取消派送任务
     * </desc>
     *
     * @param appPadBotRobotDTO 派宝机器人传参DTO
     * @return
     * @Author Zhu.yj
     * @createDate  2021/1/6
     */
    @UnAuthAccessRequired
    @PostMapping("cancelDeliveryTask")
    public Object cancelDeliveryTask(AppPadBotRobotDTO appPadBotRobotDTO, HttpServletRequest request){
        try{
            appPadBotRobotDTO = HttpProtocolUtil.parseRequestParamToDTO(AppPadBotRobotDTO.class, request);
            if (appPadBotRobotDTO == null|| StringUtils.isBlank(appPadBotRobotDTO.getTaskId())){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            boolean cancelStatus = iPadBotRobotServiceClient.cancelDeliveryTask(appPadBotRobotDTO);
            if (cancelStatus){
                return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
            }
            return new MessageVO(AppErrorCodeEnum.CANCEL_DELIVERY_TASK_FAILED.getErrorCode());
        }catch (Exception e){
            throw new DataAccessException("【派宝机器人cancelDeliveryTask】取消派送任务失败", e);
        }
    }

    /**
     * <desc>
     *      用户下单
     * </desc>
     *
     * @param
     * @return
     * @Author Zhu.yj
     * @createDate  2021/1/8
     */
    @UnAuthAccessRequired
    @PostMapping("submitOrder")
    public Object submitOrder(HttpServletRequest request){
        try{
            String goodsInfo = request.getAttribute("goodsInfo") == null ? null : request.getAttribute("goodsInfo").toString();
            String targetPointId = request.getAttribute("targetPointId") == null ? null : request.getAttribute("targetPointId").toString();
            String phoneNumber = request.getAttribute("phoneNumber") == null ? null : request.getAttribute("phoneNumber").toString();
            if (StringUtils.isBlank(goodsInfo) || StringUtils.isBlank(targetPointId) || StringUtils.isBlank(phoneNumber)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            AppPadBotRobotDTO appPadBotRobotDTO = new AppPadBotRobotDTO();
            List<Map> goodsInfoList = JSONArray.parseArray(goodsInfo, Map.class);
            appPadBotRobotDTO.setGoodsInfoList(goodsInfoList);
            //配送位置为前台，目标点根据用户写死
            appPadBotRobotDTO.setLoadingPointId(RECEPTION);
            //目前和前端调试，没有token，默认派送地址软件部
            appPadBotRobotDTO.setPhoneNumber(phoneNumber);
            appPadBotRobotDTO.setTargetPointId(targetPointId);
            iPadBotRobotServiceClient.createDeliveryTask(appPadBotRobotDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e){
            throw new DataAccessException("【派宝机器人submitOrder】用户下单失败", e);
        }
    }

    /**
     * <desc>
     *      机器人取物(2021/5/24日修改)
     * </desc>
     *
     * @return
     * @Author Zhu.yj
     * @createDate  2021/1/8
     */
    @PostMapping("robotFetch")
    public Object robotFetch(HttpServletRequest request){
        try{
            String goodsInfo = request.getAttribute("goodsInfo") == null ? null : request.getAttribute("goodsInfo").toString();
            String token = request.getAttribute("token") == null ? null : request.getAttribute("token").toString();
            String targetPointId = request.getAttribute("targetPointId") == null ? null : request.getAttribute("targetPointId").toString();
            if (StringUtils.isBlank(goodsInfo) || StringUtils.isBlank(token) || StringUtils.isBlank(targetPointId)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            AppUserCacheVO userCacheVO = userCache.retrieve(token);
            AppPadBotRobotDTO appPadBotRobotDTO = new AppPadBotRobotDTO();
            List<Map> goodsInfoList = JSONArray.parseArray(goodsInfo, Map.class);
            appPadBotRobotDTO.setGoodsInfoList(goodsInfoList);
            //配送位置为前台
            appPadBotRobotDTO.setLoadingPointId(RECEPTION);
            appPadBotRobotDTO.setPhoneNumber(userCacheVO.getPhoneNo());
            appPadBotRobotDTO.setTargetPointId(targetPointId);
            iPadBotRobotServiceClient.createDeliveryTask(appPadBotRobotDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e){
            throw new DataAccessException("【派宝机器人submitOrder】用户下单失败", e);
        }
    }

    /**
     * <desc>
     *      设置用户及目标点对应关系
     * </desc>
     *
     * @param phoneNum  手机号
     * @param targetPointId  目标点id
     * @return
     * @Author Zhu.yj
     * @createDate  2021/1/25
     */
    @UnParamEncrypt
    @UnAuthAccessRequired
    @PostMapping("setUserTarget")
    public Object setUserTarget(String phoneNum, String targetPointId){
        try {
            if (StringUtils.isBlank(phoneNum) || StringUtils.isBlank(targetPointId)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            redisService.set(RedisConstant.PADBOT_TARGET_POT_PHONE_CACHE_KEY + phoneNum, targetPointId);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), RedisConstant.PADBOT_TARGET_POT_PHONE_CACHE_KEY + phoneNum +" ,value: "+  targetPointId);
        }catch (Exception e){
            throw new DataAccessException("【派宝机器人setUserTarget】设置用户及目标点对应关系失败", e);
        }
    }

    /**
     * <desc>
     *      创建派送任务
     * </desc>
     *
     * @param appPadBotRobotDTO 派宝机器人传参DTO
     * @param request
     * @return
     * @Author Zhu.yj
     * @createDate  2021/1/8
     */
    @UnAuthAccessRequired
    @PostMapping("/createDeliveryTask")
    public Object createDeliveryTask(AppPadBotRobotDTO appPadBotRobotDTO, HttpServletRequest request){
        try {
            appPadBotRobotDTO = HttpProtocolUtil.parseRequestParamToDTO(AppPadBotRobotDTO.class, request);
            if (appPadBotRobotDTO == null || StringUtils.isBlank(appPadBotRobotDTO.getLoadingPointId())
                    || StringUtils.isBlank(appPadBotRobotDTO.getTargetPointId())
                    || StringUtils.isBlank(appPadBotRobotDTO.getPhoneNumber())){

                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            String password = iPadBotRobotServiceClient.createDeliveryTask(appPadBotRobotDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), (Object) password);
        }catch (Exception e){
            throw new DataAccessException("【派宝机器人createDeliveryTask】创建派送任务失败", e);
        }
    }
    /**
     * <desc>
     *      获取配送任务列表
     * </desc>
     *
     * @param deliveryTaskDTO 配送任务参数DTO
     * @return
     * @Author Zhu.yj
     * @createDate  2021/1/8
     */
    @UnAuthAccessRequired
    @PostMapping("getDeliveryTaskList")
    public Object getDeliveryTaskList(PropertyPadBotDeliveryTaskDTO deliveryTaskDTO, HttpServletRequest request){
        try{
            deliveryTaskDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyPadBotDeliveryTaskDTO.class, request);
            Page<PropertyDeliveryTaskGetPageVO> getPageVOList  = iPropertyDeliveryTaskServiceClient.getPage(deliveryTaskDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), getPageVOList);
        }catch (Exception e){
            throw new DataAccessException("【派宝机器人getDeliveryTaskList】获取配送任务列表失败", e);
        }
    }

    /**
     * <desc>
     *      获取地址列表
     * </desc>
     *
     * @param appPadBotRobotDTO
     * @return
     * @Author Zhu.yj
     * @createDate  2021/1/18
     */
    @PostMapping("getAddressList")
    public Object getAddressList(AppPadBotRobotDTO appPadBotRobotDTO, HttpServletRequest request) throws Exception{
        try{
            appPadBotRobotDTO = HttpProtocolUtil.parseRequestParamToDTO(AppPadBotRobotDTO.class, request);
            if (appPadBotRobotDTO == null){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            AppUserCacheVO userCacheVO = userCache.retrieve(appPadBotRobotDTO.getToken());
            if (userCacheVO == null){
                userCacheVO = new AppUserCacheVO();
            }
            List<Map<String, Object>> targetPointList = iPropertyDeliveryTaskServiceClient.getTargetPointList(userCacheVO.getPhoneNo());
            for (Map<String, Object> addressMap : targetPointList){
                addressMap.put("realName", userCacheVO.getUserName());
                addressMap.put("phoneNumber", userCacheVO.getPhoneNo());
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), targetPointList);
        }catch (Exception e){
            throw new DataAccessException("【派宝机器人getAddressList】获取目标点列表失败", e);
        }
    }

    /**
     * <desc>
     *      设置地图id
     * </desc>
     *
     * @param
     * @return
     * @Author Zhu.yj
     * @createDate  2021/1/28
     */
    @UnParamEncrypt
    @UnAuthAccessRequired
    @PostMapping("setMapId")
    public Object setMapId(String mapId){
        try{
            if (StringUtils.isBlank(mapId)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            redisService.set(RedisConstant.PADBOT_MAP_ID_CACHE_KEY, mapId);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), redisService.get(RedisConstant.PADBOT_MAP_ID_CACHE_KEY));
        }catch (Exception e){
            throw new DataAccessException("【机器人派送任务cancelDeliveryTask】获取目标点列表失败", e);
        }
    }

    /**
     * <desc>
     *      获取用户的目标点
     * </desc>
     *
     * @param
     * @return
     * @Author Zhu.yj
     * @createDate  2021/5/16
     */
    @PostMapping("getUserTargetId")
    public Object getUserTarget(HttpServletRequest request){
        try {
            String token = request.getAttribute("token") == null ? null : request.getAttribute("token").toString();
            if (token == null){
                return new MessageVO(BaseErrorCodeEnum.PARAM_ERR.getErrorCode());
            }
            AppUserCacheVO appUserCacheVO = userCache.retrieve(token);
            if (appUserCacheVO == null || StringUtils.isBlank(appUserCacheVO.getUserId()) || StringUtils.isBlank(appUserCacheVO.getPhoneNo())){
                return new MessageVO(BaseErrorCodeEnum.ERROR.getErrorCode(), "禁止调用");
            }
            String targetPointId = redisService.get(RedisConstant.PADBOT_TARGET_POT_PHONE_CACHE_KEY + appUserCacheVO.getPhoneNo());
            if (StringUtils.isBlank(targetPointId)){
                //没找到地图，默认软件部
                targetPointId = SOFTWARE_DEPARTMENT;
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), (Object)targetPointId);
        }catch (Exception e){
            throw new DataAccessException("【机器人派送任务cancelDeliveryTask】获取用户绑定的目标点失败", e);
        }

    }

}
